package com.learn.spring_jdbc.dao;

import com.learn.spring_jdbc.bean.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class AccountDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    // 新增
    public int addAccount(String name, double money) {
        return jdbcTemplate.update(
                "INSERT INTO account (name, money) VALUES (?, ?)", name, money
        );
    }
    
    // 删除
    public int deleteAccount(int id) {
        return jdbcTemplate.update(
                "DELETE FROM account WHERE id = ?", id
        );
    }
    
    // 修改
    public int updateAccount(int id, String name, double money) {
        return jdbcTemplate.update(
                "UPDATE account SET name = ?, money = ? WHERE id = ?", name, money, id
        );
    }
    
    // 查询
    public List<Account> getAllAccounts() {
        return jdbcTemplate.query(
                "SELECT * FROM account", new BeanPropertyRowMapper<Account>(Account.class)
        );
    }
    
    // 根据id查询
    public Account getAccountById(int id) {
        try {
            return jdbcTemplate.queryForObject(
                    "SELECT * FROM account WHERE id = ?",
                    new BeanPropertyRowMapper<Account>(Account.class), id
            );
        } catch (Exception e) {
            return null;
        }
    }
}
